package com.lc.yygh.order.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.YYGH.common.exception.YyghException;
import com.lc.YYGH.common.result.ResultStatus;
import com.lc.YYGH.enums.OrderStatusEnum;
import com.lc.YYGH.helper.HttpRequestHelper;
import com.lc.YYGH.hospclient.HospitalFeignClient;
import com.lc.YYGH.model.user.Patient;
import com.lc.YYGH.rabbit.MqConst;
import com.lc.YYGH.rabbit.RabbitService;
import com.lc.YYGH.userclient.PatientFeginClient;
import com.lc.YYGH.vo.hosp.ScheduleOrderVo;
import com.lc.YYGH.vo.msm.MsmVo;
import com.lc.YYGH.vo.order.*;
import com.lc.yygh.order.mapper.OrderInfoMapper;
import com.lc.yygh.order.service.OrderInfoService;
import org.springframework.util.StringUtils;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private HospitalFeignClient hospitalFeignClient;
    @Autowired
    private PatientFeginClient patientFeginClient;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private RabbitService rabbitService;
    @Transactional(rollbackFor = Exception.class)

    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //就诊人信息
        System.out.println("打印病人"+scheduleId+patientId);
        Patient patient=patientFeginClient.getPatientById(patientId);
        System.out.println("打印病人信息"+patient);
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);
        System.out.println("打印排班订单信息-----"+scheduleOrderVo);
//        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
//         ||new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()){
//            throw new YyghException(ResultStatus.FAIL);
//        }
        SignInfoVo signInfoVo=hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());
        System.out.println("打印签名信息------"+signInfoVo);
        OrderInfo orderInfo=new OrderInfo();
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);
        String outTradeNo=System.currentTimeMillis()+""+new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);
        orderInfo.setHosScheduleId(scheduleId);
        orderInfo.setUserId(patient.getUserId());
        orderInfo.setPatientId(patientId);
        orderInfo.setPatientName(patient.getName());
        orderInfo.setPatientPhone(patient.getPhone());
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        baseMapper.insert(orderInfo);
        //调用医院接口，封装调用接口所需的参数，这些参数放在map中
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getHosScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());

        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());

        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);
        System.out.println("param----"+paramMap);
        System.out.println("----"+signInfoVo.getApiUrl());

        //请求医院系统接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl() + "/order/submitOrder");


        if(result.getInteger("code")==200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");
            //ToDo
            //发送mq消息，号源更新和短信通知
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);
            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());

            if(orderInfo.getReserveTime()==null)
            {
                orderInfo.setReserveTime(1);
            }
            String reserveDate = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd") + (orderInfo.getReserveTime()==0 ? "上午" : "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
                put("code","6666");
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);

            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);
        } else {
            throw new YyghException(result.getString("message"), ResultStatus.FAIL.getCode());
        }
        return orderInfo.getId();

    }

    @Override
    public void patientTips() {

    }

    @Override
    public Map<String, Object> getOrderCountMap(OrderCountQueryVo orderCountQueryVo) {
        List<OrderCountVo> orderCountVoList=orderInfoMapper.selectOrderCountVo(orderCountQueryVo);
        Stream<OrderCountVo> stream = orderCountVoList.stream();
     List<String> revers=stream.map(vo->vo.getReserveDate()).collect(Collectors.toList());
        //获取所有count值的集合
        List<Integer> counts = orderCountVoList.stream().map(vo -> vo.getCount()).collect(Collectors.toList());
        Map<String,Object> map=new HashMap<>();
        map.put("dateList",revers);
        map.put("countList",counts);
        return map;
    }

    @Override
    public OrderInfo getById(Long id) {
        OrderInfo orderInfo=baseMapper.selectById(id);
        return this.packOrderInfo(orderInfo);
    }

    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        String name=orderQueryVo.getKeyword();
        Long patientId=orderQueryVo.getPatientId();
        String orderStatus=orderQueryVo.getOrderStatus();
        String reserveDate=orderQueryVo.getReserveDate();
        String createTimeBegin=orderQueryVo.getCreateTimeBegin();
        String createTimeEnd=orderQueryVo.getCreateTimeEnd();
        QueryWrapper<OrderInfo> wrapper=new QueryWrapper<>();

        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(String.valueOf(patientId))) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法

        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;
    }

    private OrderInfo packOrderInfo(OrderInfo orderInfo)
    {
        orderInfo.getParam().put("orderStatusString",OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }


}
